package net.xi.news.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import net.xi.news.dao.ImagesMapper;
import net.xi.news.pojo.Images;
import net.xi.news.service.ImagesService;
import net.xi.news.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Slf4j
@Service
public class ImagesServiceImpl extends ServiceImpl<ImagesMapper, Images> implements ImagesService {

    @Autowired
    private RedisService redisService;

    /**
     * 首页轮播图
     * @return
     */
    @Override
    public Page<Images> imagesPage(Images.Type type){
        String imagesison = redisService.get("NEWS_IMAGES_"+type);
        log.info("从缓存中获取轮播图："+imagesison);
        if (StringUtils.isEmpty(imagesison)){
            QueryWrapper<Images> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("type",type);
            queryWrapper.orderByDesc("num");
            Page<Images> imagesPage = this.page(new Page<Images>(1, 5),queryWrapper);
            String s = JSON.toJSONString(imagesPage.getRecords());
            redisService.set("NEWS_IMAGES_"+type,60*60*24,s);
            return imagesPage;
        }else {
            List<Images> images = JSON.parseArray(imagesison, Images.class);
            Page<Images> objectPage = new Page<>(1,5);
            objectPage.setRecords(images);
            return objectPage;
        }

    }

    public static void main(String[] args) {
        System.out.println(Images.Type.INDEX);
        System.out.println(Images.Type.WIKI);
    }

}
